package com.acwebsitedesign.uRateDrugs.web;

import java.sql.SQLException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Validator;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;

import com.acwebsitedesign.uRateDrugs.domain.Account;
import com.acwebsitedesign.uRateDrugs.domain.AccountService;
import com.acwebsitedesign.uRateDrugs.domain.AccountValidator;

@Controller
@SessionAttributes("newUser")
public class CreateAccountController {

	@Autowired
	AccountService accountService;
	@Autowired
	Validator validator;
	
	public void setValidator(Validator validator) {
		this.validator = validator;
	}

	@RequestMapping("/createNewUser.html")
	public ModelAndView newUser() {

		Account newUser = new Account();
		ModelAndView mav = new ModelAndView("newUser");
		mav.addObject("newUser", newUser);
		return mav;
	}

	@RequestMapping("/confirmNewUser.html")
	public ModelAndView confirmNewUser(@RequestParam String submit,
			@ModelAttribute("newUser") Account newUser, BindingResult result)
			throws SQLException {
		
		boolean usernameAvailable = accountService.isUsernameAvailable(newUser.getUsername());
		if (!(usernameAvailable)){
			ModelAndView mav = new ModelAndView("usernameUnavailable");
			mav.addObject("newUser", newUser);
			return mav;
		}

		validator.validate(newUser, result);
		AccountValidator accountValidator = new AccountValidator();
		accountValidator.validate(newUser, result);
		if (result.hasErrors()) {
			return new ModelAndView("newUser");
		}

		ModelAndView mav = new ModelAndView("confirmUser");
		mav.addObject("newUser", newUser);
		return mav;
	}

	@RequestMapping("/thanks.html")
	public ModelAndView saveNewUser(@ModelAttribute("newUser") Account newUser) {

		accountService.save(newUser);
		ModelAndView mav = new ModelAndView("thanks");
		mav.addObject(newUser);
		return mav;
	}
	

}